package com.example.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSON;
import com.example.model.ActionResult;

import lombok.extern.slf4j.Slf4j;

/**
 * rest接口返回值统一包装实现
 *
 * @author changwei
 * @date 2018年9月10日
 */
@Slf4j
@ControllerAdvice(basePackages="com.example")
public class RestResultResponseBodyAdvice implements ResponseBodyAdvice<Object>{

//	private List<String> scanPackages;
	
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		/*String pkgName = controllerClass.getName();
		List<String> scanPks = this.getScanPackages();
		for(String pk : scanPks) {
			if(pkgName.startsWith(pk)) {
				return true;
			}
		}*/
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		if(body == null) {
			body = ActionResult.success().build();
		} else if(!(body instanceof ActionResult)){
			body = ActionResult.success().withData(body).build();
		}
		log.trace("框架内部请求将范围值统一包装.actionResult:{}", body);
		if(StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
			//TODO 此处是否可考虑根据returnType做为判断条件更合理
			body = JSON.toJSONString(body);
			log.trace("将ActionResult序列化json字符串.body:{}", body);
		}
		return body;
	}

	/*private List<String> getScanPackages() {
		if(scanPackages != null) {
			return scanPackages;
		}
		scanPackages = AutoConfigurationPackages.get(SpringUtils.getBeanFactory());
		return scanPackages;
	}*/
}
